package cn.hg.base.kit;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jfinal.core.Controller;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;
import com.jfinal.upload.UploadFile;

/**
 * @author Golly
 */
public class UploadFileKit {

	public static List<Map<String, String>> uploadFile (String folder, Controller c) {
		List<Map<String, String>> list = new ArrayList<>();
		List<UploadFile> uploadList = c.getFiles();

		if (uploadList.size() == 0) {
			LogKit.warn("没有获取到上传文件！");
			return list;
		}

		// 上传时的相对路径
		String uri = UploadFileKit.getDirUri(folder);
		// 项目的基础路径
		String basePath = PathKit.getWebRootPath();
		int count = 0;

		for (UploadFile upload : uploadList) {
			Map<String, String> data = new HashMap<>();
			String newName = UploadFileKit.getFileName(upload.getFileName());
			String path = upload.getUploadPath() + uri;
			UploadFileKit.createPath(basePath + path);
			File destFile = new File(basePath + path + newName);
			File srcFile = upload.getFile();
			srcFile.renameTo(destFile);
			data.put("imgUrl" + count, UploadFileKit.getUrl(c, path, newName));
			list.add(data);
			count++;
		}

		return list;
	}

	/**
	 * 创建物理路径
	 *
	 * @param path
	 */
	private static void createPath (String path) {
		File f = new File(path);

		if (!f.exists()) {
			f.mkdirs();
		}

	}

	/**
	 * 在目标上传路径中加上日期路径
	 *
	 * @param folder
	 *
	 * @return
	 */
	private static String getDirUri (String folder) {
		StringBuilder sb = new StringBuilder();
		sb.append(File.separator);

		if (!StrKit.isBlank(folder)) {
			sb.append(folder).append(File.separator);
		}

		return sb.toString();
	}

	/**
	 * 生成新名字
	 *
	 * @param newName
	 *
	 * @return
	 */
	private static String getFileName (String newName) {
		return newName;
		// return newName.substring(0, newName.lastIndexOf(".")) + new Date().getTime() +
		// newName.substring(newName.lastIndexOf("."));
	}

	/**
	 * 将目标路径的分隔符转换为URL的分隔符"/"
	 *
	 * @param uri
	 * @param name
	 *
	 * @return
	 */
	private static String getUrl (Controller c, String uri, String name) {
		uri = c.getRequest().getContextPath() + uri;
		return uri.replaceAll("\\\\", "/") + name;
	}

}
